import { io } from "socket.io-client";
import { ElMessage } from "element-plus";
import { useStore } from "@/store/modules/user";
import { adminStorage } from '@/utils/storage'
import { ref } from "vue";

class myWebSocket {
  constructor({ url, otp = { message: true, keyValue: 'pushMsg' } }) {
    this.store = useStore();
    // this.url = url || 'ws://localhost:8765' // 指定默认ws的地址
    // this.url = url || 'ws://107.151.249.219:9999'  // 指定默认ws的地址 
    // this.url = url || `ws://${process.env.NODE_ENV !== 'production' ? '107.151.249.219:9999' :'107.151.249.219:9999'}`  // 指定默认ws的地址 

    this.url = url || process.env.NODE_ENV !== 'production' ? 'ws://localhost:8777' : 'ws://111.92.241.91:9999'    
    // this.url ='ws://localhost:8777'
    this.socket = null // 实例化的ws对象
    this.messageArr = ref([])  // 接收服务端推送的消息
    this.otp = otp
  }
  createFn(namespace = '/admin', path = '/socketIo', options = {}, callback) {
    let token = "Bearer " + adminStorage.getSession("token");
    try {
      this.socket = io.connect(this.url + namespace, {
        path,
        query: { auth: options.username || '', room: options.user || '' },
        auth: { token }
      })
      console.log(this.socket,'this.socket');
      // 连接开启
      this.socket.on("connect", () => {
        console.log('连接成功', this.otp.keyValue)
        if (this.otp.message) ElMessage({
          message: '连接成功',
          type: "success",
        });
       
        this.socket.on(this.otp.keyValue, (data) => {
          console.log(`接收${this.otp.keyValue}消息`, data)
          this.messageArr.value = data
          if (!this.otp.message && this.otp.keyValue === 'sendInfo') {
            this.store.SET_MSG(data)
          }
        })
        if (typeof callback === 'function') callback(this.socket)
      });
      

      this.socket.on("disconnect", (reason) => {
        // ...连接中断
        console.error('连接中断')
      });
      // 连接错误
      this.socket.on("connect_error", () => {
        console.error('连接错误')
        this.closeFn()
      });
    } catch (error) {
      console.error('出错了', error)
      this.socket = null
      this.closeFn()
    }
  }
  // 客户端主动发消息
  sendFn(key = 'sendMsg', msg, callback) {
    if (!this.socket) {
      console.warn('WebSocket未连接 无法发消息')
      return
    }
    msg = msg || 'hellow'
    this.socket.emit(key, {
      message: msg
    })
    if (this.otp.message) ElMessage({
      message: '发送消息成功',
      type: "success",
    });
    if (typeof callback === 'function') callback(this.socket)
  }
  closeFn() {
    if (!this.socket) {
      console.warn('WebSocket未连接 不需要关闭')
      return
    }
    if (this.otp.message) ElMessage({
      message: '关闭成功',
      type: "success",
    });
    this.socket.disconnect()
    this.socket = null
    this.messageArr = []
    this.connectCount = 0
  }

}

export default myWebSocket